import { AppRouteConfig } from "@components/Apps/AppRouteConfig";
import HomeContent from "@components/Apps/Simulation/HomeContent";
import AppSettings from "@runtime/base/AppSettings";
import { ClientMessage } from "@runtime/generate/message/ClientMessage";
import RouterComponent from "@runtime/module/Router/RouterComponent";
import SessionStorageComponent from "@runtime/module/SessionStorage/SessionStorageComponent";
import WebSocketComponent from "@runtime/module/WebSocket/WebSocketComponent";
import { ref, Ref } from "vue";

/**
 * 启动界面
 */
export default class SplashComponent {
    private static instance: SplashComponent = new SplashComponent();
    /**
     * 启动界面
     */
    public static get Default(): SplashComponent {
        return this.instance;
    }

    constructor() {
        window.addEventListener('unload', this.Dispose.bind(this));
    }

    Dispose() {
        window.removeEventListener('unload', this.Dispose);
    }

    public Tip: Ref<string> = ref('加载中···');
    public IsLoading: Ref<boolean> = ref(true);
    private Types: boolean = false;
    public async InitializeAsync(): Promise<void> {
        if (this.Types) {
            return
        }
        window.Logger.Information(`应用启动中···`);
        if (import.meta.env.PROD) {
            // 加载启动参数
            const settings = await SessionStorageComponent.Default.ReadAsAsync<AppSettings>(SessionStorageComponent.CommandLineArgsKey, 100, 1000 * 10);
            if (settings == null) {
                this.Tip.value = '初始化启动参数失败';
                return;
            }

            // 启动参数赋值
            AppSettings.Copy(settings, AppSettings.Default);

            // 连接本地主机
            if (!await WebSocketComponent.Default.ConnectAsync()) {
                this.Tip.value = '初始化连接失败';
                return;
            }

            // 通知本地主机初始化完成
            WebSocketComponent.Default.PostMessage(new ClientMessage.WebInitializedMessage());
        } else {
            AppSettings.Default.Id = 0;
            AppSettings.Default.ShortName = 'P00000';
        }

        AppSettings.Default.Type = 'Simulation';

        // 添加动态路由
        // RouterComponent.Default.AddDynamicRoute(AppRouteConfig);

        window.Logger.Information(`应用已启动(${AppSettings.Default.Type})`);

        //@ts-ignore
        console.log(JSON.parse(sessionStorage.getItem('CommandLineArgs')).StartupParameter);  // {}
        //@ts-ignore
        if (JSON.parse(sessionStorage.getItem('CommandLineArgs')).StartupParameter != '{}') {
            //@ts-ignore
            HomeContent.Default.ProductName.value = JSON.parse(decodeURIComponent(escape(window.atob(JSON.parse(sessionStorage.getItem('CommandLineArgs')).StartupParameter)))).ProductType
            console.log('产品名',HomeContent.Default.ProductName.value);
            
        }


        // 根据启动参数切换路由
        // await RouterComponent.Default.NavigateToAsync(`/${AppSettings.Default.Type}`);
        this.Types = true
    }
}